package com.nio;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class NioSocket {

	
	
	public void start() throws Exception{
		
		int channels = 0;
		
		int nKeys = 0;
		
		int currSelector = 0;
		
		Selector selector = Selector.open();
		
		ServerSocketChannel ssc = ServerSocketChannel.open();
		
		InetSocketAddress addr = new InetSocketAddress(9000);
		
		ssc.socket().bind(addr);
		
		ssc.configureBlocking(false);
		
		SelectionKey key = ssc.register(selector, SelectionKey.OP_ACCEPT);
		
		System.out.println(key.toString());
		
		while (true){
			
			System.out.println("Starting select...");
			
			nKeys = selector.select();
			
			if (nKeys <= 0 ) {
				System.out.println("Select finished without any keys.");
				continue;
			}
			
			System.out.println("Number of keys after select operation:" + nKeys);
			
			Set selectedKeys = selector.selectedKeys();
			
			Iterator i = selectedKeys.iterator();
			
			while (i.hasNext()){
			
				key = (SelectionKey)i.next();
				
				System.out.println(key.toString());
				
				System.out.println("Nr Keys in selector: " + selectedKeys.size());
				
				i.remove();
				
				if (key.isAcceptable()){
					
					Socket socket = ((ServerSocketChannel)key.channel()).accept().socket();
					
					SocketChannel sc = socket.getChannel();
					
					sc.configureBlocking(false);
					
					sc.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);
					
					System.out.println(++channels);
					
				}
			}
			
		}
		
		
	}
}
